package model

import (
	"github.com/DanPlayer/randomname"
	"golang.org/x/crypto/bcrypt"
	"gorm.io/gorm"
)

type User struct {
	UserAccount string `gorm:"type:varchar(255);comment:账户;column:user_account;not null"`
	Username    string `gorm:"type:varchar(255);comment:昵称;column:username"`
	Password    string `gorm:"type:varchar(255);comment:密码;column:password;not null"`
	Profile     string `gorm:"type:varchar(255);comment:简介;column:profile"`
	Role        string `gorm:"type:varchar(255);comment:角色;column:role"`
	gorm.Model
}

func (User) TableName() string {
	return "user"
}
func (User) TableComment() string {
	return "用户表"
}

type UserVo struct {
	ID          uint
	UserAccount string `json:"userAccount"`
	Username    string `json:"username"`
	Password    string `json:"password"`
	Profile     string `json:"profile"`
	Role        string `json:"role"`
}

type UserDto struct {
	UserAccount string `json:"userAccount"`
	Username    string `json:"username"`
	Password    string `json:"password"`
	Profile     string `json:"profile"`
	Role        string `json:"role"`
}

type LoginForm struct {
	UserAccount string `json:"userAccount" required:"true"`
	Password    string `json:"password" required:"true"`
}

type RegisterForm struct {
	UserAccount string `json:"userAccount" required:"true"`
	Password    string `json:"password" required:"true"`
}

// BeforeSave hook
func (u *User) BeforeSave(tx *gorm.DB) error {
	hashedPassword, err := bcrypt.GenerateFromPassword([]byte(u.Password), bcrypt.DefaultCost)
	if err != nil {
		return err
	}
	u.Password = string(hashedPassword)
	u.Username = randomname.GenerateName()
	return nil
}
